package com.cyx.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取资源路径
        String filePath = getServletContext().getRealPath("WEB-INF/classes/images/猴子.png");
        System.out.println(filePath);
        String filename = filePath.substring(filePath.lastIndexOf("\\")+1);
        //2、设置浏览器头,让浏览器支持文件下载,注意如果存在中文需要转码
        resp.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(filename,"UTF-8"));
        //3、通过流输出
        FileInputStream input = new FileInputStream(filePath);
        ServletOutputStream out = resp.getOutputStream();
        try{
            byte[] buffer = new byte[1024];

            int len = 0;
            while((len = input.read(buffer)) >0){
                out.write(buffer,0,len);
            }
        }finally {
            input.close();
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
